
//
//  CustomerScrollWidthScrollView.swift
//  Krungm
//
//  Created by edy on 2025/7/7.
//


protocol CustomerScrollWidthScrollViewDataSource: NSObjectProtocol {
    func datas() -> [Any]
    func view(index: Int) -> UIView
    
    func currentItemIndex(index: Int)
}

class CustomerScrollWidthScrollView: UIView, UIScrollViewDelegate {
    
    
    weak open var dataSource: (any CustomerScrollWidthScrollViewDataSource)?
    
    var itemWidth: CGFloat
    var itemSpacing: CGFloat
    var leftRightInset: CGFloat
    private var pageWidth: CGFloat = 0
    
    init(itemWidth: CGFloat = UIScreen.main.bounds.width - 60,
         itemSpacing: CGFloat = 10,
         leftRightInset: CGFloat = 30) {
        self.itemWidth = itemWidth
        self.itemSpacing = itemSpacing
        self.leftRightInset = leftRightInset
        self.pageWidth = itemWidth + itemSpacing
        super.init(frame: .zero)
    }
    
    
    func reloadData() {
        if dataSource == nil { return }
        for v in scrollView.subviews {
            v.removeFromSuperview()
        }
        for i in 0..<(dataSource!.datas().count) {
            let frame = CGRect(x: CGFloat(i) * pageWidth, y: 0, width: itemWidth, height: self.frame.height)
            let view = dataSource!.view(index: i)
            view.frame = frame
            scrollView.addSubview(view)
        }
        
        scrollView.contentSize = CGSize(width: CGFloat(dataSource!.datas().count) * pageWidth, height: 200)
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    override func layoutSubviews() {
        scrollView.frame = self.bounds
    }
    
    lazy var scrollView: UIScrollView = {
        let _sv = UIScrollView()
        _sv.showsHorizontalScrollIndicator = false
        _sv.decelerationRate = .fast
        _sv.delegate = self
        _sv.contentInset = UIEdgeInsets(top: 0, left: leftRightInset, bottom: 0, right: leftRightInset)
        self.addSubview(_sv)
        return _sv
    }()
    
    func scrollViewWillEndDragging(_ scrollView: UIScrollView, withVelocity velocity: CGPoint, targetContentOffset: UnsafeMutablePointer<CGPoint>) {
        let targetX = targetContentOffset.pointee.x
        let page = round((targetX + scrollView.contentInset.left) / pageWidth)
        let newTargetX = page * pageWidth - scrollView.contentInset.left
        targetContentOffset.pointee = CGPoint(x: newTargetX, y: targetContentOffset.pointee.y)
        dataSource?.currentItemIndex(index: Int(page))
    }
}
